package sample.client;

import io.netty.channel.ChannelHandler.Sharable;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import sample.vo.TestP0002;
import tech.mhuang.pacebox.netty.vo.BaseRespMessage;



/**
 * @author mHuang
 * @version V1.0.0
 * @Description netty 客户端处理
 * @date 2015年7月16日 下午3:40:09
 */
@Sharable
public class TestNettyClientHandler extends SimpleChannelInboundHandler<BaseRespMessage> {

    private static final Logger logger = LoggerFactory.getLogger(TestNettyClientHandler.class);

    /**
     * Description  链接成功后执行..
     *
     * @param ctx
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) {
        System.out.println(ctx.channel().id().asLongText());
        System.out.println("client connection success");
//		P0100 login = new P0100();
//		ctx.writeAndFlush(login);
    }

    /**
     * Description 客户端异常
     *
     * @param ctx
     * @param cause
     */
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        try {
            super.exceptionCaught(ctx, cause);
        } catch (Exception e) {
            logger.info("client exception ....关闭连接");
            ctx.close();
        }
    }


    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if (evt instanceof IdleStateEvent event) {
            if (event.state() == IdleState.READER_IDLE) {
                logger.info("读取数据超时~~");
//				ctx.close();
            } else if (event.state() == IdleState.WRITER_IDLE) {
                logger.info("写入超时、发送心跳包！");
                //写的心跳数据
                TestP0002 heart = new TestP0002();
                heart.setBody("你好".getBytes("GBK"));
                ctx.writeAndFlush(heart);
            }
        }
        super.userEventTriggered(ctx, evt);
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, BaseRespMessage msg) throws Exception {
        System.out.println(msg.getHeader().getMsgId() + "----" + msg.getHeader().getResult() + new String(msg.getBody(), "gbk"));
    }
}
